import QRCode from 'qrcode';
import { ceil } from 'lodash';

export function savePicToLocal(url = '', name = '') {
  if (!url) return;
  const link = document.createElement('a');
  link.href = url; // 下载链接
  link.setAttribute('download', `${name}.png`);
  link.style.display = 'none'; // a标签隐藏
  document.body.appendChild(link);
  link.click();
  setTimeout(() => {
    link.parentNode.removeChild(link);
  }, 0);
}

export const formatImgForCanvas = (url, w = 100, h = 100) => {
  if (!url) return '';
  // eslint-disable-next-line no-use-before-define
  url = http2https(url);
  url = url.replace(
    'image-process-service.oss-cn-shanghai.aliyuncs.com',
    'ips-cdn.aikucun.com'
  );
  if (url.match(/.*?\.gif/i)) return url;
  let formattedUrl = url;
  if (url.includes('akim.oss-cn-shanghai.aliyuncs.com')) {
    formattedUrl = url.replace(
      /akim\.oss-cn-shanghai\.aliyuncs\.com/,
      'akmer.aikucun.com'
    );
  } else if (url.includes('devdev.oss-cn-shanghai.aliyuncs.com')) {
    formattedUrl = url.replace(
      /devdev\.oss-cn-shanghai\.aliyuncs\.com/,
      'devdev.cdn.akucun.com'
    );
  }
  // eslint-disable-next-line no-use-before-define
  formattedUrl = _formatImgUrl(formattedUrl, w, h);
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.onload = () => {
      img = null;
      resolve(formattedUrl);
    };
    img.onerror = () => {
      img = null;
      const error = Error(`${formattedUrl}图片渲染失败`);
      reject(error);
    };
    img.src = formattedUrl;
  });
};

const _formatImgUrl = (url, w = 100, h = 100, mode = 'mfit', format) => {
  if (!url) return '';
  if (url.match(/.*?\.gif/i)) return url;
  const dpi = Math.ceil(parseInt(window.devicePixelRatio || 2, 10)) || 2;
  if (h === 'auto') h = '';
  if (w === 'auto') w = '';
  let rw = w && ceil(dpi * w, -2);
  let rh = h && ceil(dpi * h, -2);
  let p = [];
  if (rw) {
    rw = Math.min(800, rw);
    p.push(`w_${rw}`);
  }
  if (rh) {
    p.push(`h_${rh}`);
  }
  let params = p.join(',');
  if (format) {
    // eslint-disable-next-line no-use-before-define
    return `${http2https(
      url
    )}?x-oss-process=image/format,${format}/resize,m_${mode},${params}`;
  }
  // eslint-disable-next-line no-use-before-define
  return `${http2https(url)}?x-oss-process=image/resize,m_${mode},${params}`;
};

// 生成二维码图片
const getNewQrImg = url => {
  return QRCode.toDataURL(url);
};

const formatImgUrl = (url, w = 100, h = 100, mode = 'mfit') => {
  if (!url) return '';
  const dpi = Math.ceil(parseInt(window.devicePixelRatio || 2, 10)) || 2;
  const rw = ceil(dpi * w, -2);
  const rh = ceil(dpi * h, -2);
  return `${url.replace(
    /^http[s]?:/,
    window.location.protocol || 'https:'
  )}?x-oss-process=image/resize,m_${mode},h_${rh},w_${rw}`;
};

const formatDuring = time => {
  let h = '00';
  let m = '00';
  let s = '00';
  if (time > 0) {
    h = Math.floor(time / 1000 / 60 / 60);
    m = Math.floor((time / 1000 / 60) % 60);
    s = Math.floor((time / 1000) % 60);
    h = h < 10 ? `0${h}` : h;
    m = m < 10 ? `0${m}` : m;
    s = s < 10 ? `0${s}` : s;
  }
  return h + ':' + m + ':' + s;
};

// 检查元素当前是否为聚焦状态
const elementIsInFocus = el => el === document.activeElement;

// 检查是否是苹果设备
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);

// eslint-disable-next-line no-unused-vars
const aa = () => {
  document.addEventListener('visibilitychange', function() {
    console.log(document.visibilityState);
    if (document.visibilityState == 'hidden') {
      console.log('隐藏');
    } else if (document.visibilityState == 'visible') {
      console.log('显示');
    }
  });
};

/**
 * 处理多个promise的错误
 * @param p
 * @returns {Promise<*|{err: number, data: null}>}
 */
export const promiseWithError = async p => {
  try {
    const res = await p;
    return { ...res, err: 0 };
  } catch (e) {
    return { err: 1, data: null };
  }
};

export const http2https = val => {
  if (typeof val !== 'string' || !val) {
    return val;
  }
  if (val.match(/^https:\/\//)) return val;
  const matchRes = val.match(/^(http:)\/\/([-.\w]+)\/(.+)/);
  if (matchRes && convertDomainList[matchRes[2]] === matchRes[1]) {
    return `https://${matchRes[2]}/${matchRes[3]}`;
  }
  return val;
};

// 以下经过手动验证可以进行从http协议转为https协议；
const convertDomainList = {
  'akmer.aikucun.com': 'http:',
  'mer.oss.aikucun.com': 'http:',
  'akim.oss-cn-shanghai.aliyuncs.com': 'http:',
  'thirdwx.qlogo.cn': 'http:',
  'devdev.oss-cn-shanghai.aliyuncs.com': 'http:',
  'devdev.cdn.akucun.com': 'http:',
  'devdevnew.oss.aikucun.com': 'http:',
  'image-process-service.oss-cn-shanghai.aliyuncs.com': 'http:'
};

export const minus2num = (num1 = 0, num2 = 0) => {
  let l1;
  let l2;
  try {
    l1 = num1.toString().split('.')[1].length;
  } catch (e) {
    l1 = 0;
  }
  try {
    l2 = num2.toString().split('.')[1].length;
  } catch (e) {
    l2 = 0;
  }
  const maxL = Math.max(l1, l2);
  const pow = 10 ** maxL;
  return ((num1 * pow - num2 * pow) / pow).toFixed(maxL);
};

/**
 * 获取当前url中参数
 * @param name {有值则返回当前值得参数，没有则返回全部参数[Object]}
 */
export function getUrlParam(name = null, url = null) {
  let result = {};
  let curUrl = url || window.location.href;

  curUrl = curUrl.substring(curUrl.indexOf('#')).split('?');

  if (Array.isArray(curUrl)) curUrl = curUrl.length > 1 ? curUrl[1] : null;

  if (curUrl) {
    curUrl.split('&').forEach(element => {
      if (!element) return;
      let temp = element.split('=');
      let key = temp[0];
      let value =
        typeof temp[1] === 'undefined'
          ? undefined
          : decodeURIComponent(temp[1]);
      result[key] = value;
    });
  }

  return name ? result[name] : result;
}

/**
 * 根据url地址获取query参数
 * @returns {{}}
 */
export const getQueryParams = url => {
  const search = url.split('?');
  if (search.length !== 2) {
    return {};
  }
  let queryData = {};
  let queryStrList = search[1].split('&');
  queryStrList.forEach(it => {
    let q = it.split('=');
    queryData[q[0]] = q[1];
  });
  return queryData;
};

// 资源位链接跳转的方法
export const goLink = (linkUrl, callback) => {
  // 获取链接的域名
  const urlArr = linkUrl.split('#');
  let domain = urlArr[0] || '';
  domain = domain.slice(0, domain.length - 1);

  // 获取链接的跳转path
  let path = '';
  if (urlArr.length === 2) {
    const jumpUrl = urlArr[1].split('?');
    path = jumpUrl[0].slice(1);
  }
  // 获取链接上的参数
  const params = getQueryParams(linkUrl);

  // 内部链接
  const domainList = process.env.VUE_APP_DOMAIN_LIST.split(',');
  if (domainList.includes(domain)) {
    if (typeof callback === 'function') callback(params, path);
  } else {
    // 外部链接处理
    window.location.href = linkUrl;
  }
};

// 例子如何使用
// Promise.all(promiseArr.map(p => promiseWithError(p)))
//   .then(result => {
//     this.docServiceList = this.docServiceList.map((item, index) => {
//       if (result[index] && result[index].data && item.price) {
//         const discountDetail = result[index].data || {};
//         item.payableTotalAmount = discountDetail.payableTotalAmount;
//       }
//       return item;
//     });
//   })
//   .catch(() => {
//     this.$toast('服务有误，请稍后再试');
//   });

const calcHostEnvironment = () => {
  const ua = window.navigator.userAgent.toLowerCase();
  const result = ua.match(/MicroMessenger/i);
  if (result) {
    return 'wechat';
  }
  return 'browser';
};
const currHostEnvironment = calcHostEnvironment();

export const getHostEnvironment = () => currHostEnvironment;

/**
 * 获取当前页面视口高度（兼容性写法）
 */
export function getCurPageClientHeight() {
  return (
    window.innerHeight ||
    document.documentElement.clientHeight ||
    document.body.clientHeight
  );
}
/**
 * 兼容性写法, 适配iOS 13, 12 及以下 && 安卓...各种版本
 * 暂定：
 *     window.scrollY                      第一优先级
 *     document.documentElement.scrollTop  第二优先级
 *     document.body.scrollTop             第三优先级
 *     0                                   默认值兜底
 */
export const getScrollY = () => {
  return (
    window.scrollY ||
    document.documentElement.scrollTop ||
    document.body.scrollTop ||
    0
  );
};

/**
 * 倒计时
 * @param  oldTime  '1580505514727'
 */
export const countDown = oldTime => {
  if (oldTime) {
    const currentTime = new Date().getTime();
    const differTime = Number(oldTime) - currentTime;
    let d = '00';
    let h = '00';
    let m = '00';
    let s = '00';
    let obj = {};
    if (differTime > 0) {
      d = Math.floor(differTime / 1000 / 60 / 60 / 24);
      h = Math.floor((differTime / 1000 / 60 / 60) % 24);
      m = Math.floor((differTime / 1000 / 60) % 60);
      s = Math.floor((differTime / 1000) % 60);
      obj.d = d < 10 ? `0${d}` : d;
      obj.h = h < 10 ? `0${h}` : h;
      obj.m = m < 10 ? `0${m}` : m;
      obj.s = s < 10 ? `0${s}` : s;
      obj.isOver = false;
    } else {
      obj.isOver = true;
    }
    return obj;
  }
  return '参数为必填项';
};

export const plateform = (global => {
  const ua = global.navigator.userAgent;
  const isiOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  const isAndriod = ua.includes('Android');
  const isWeixin = !!ua.match(/MicroMessenger/);
  const isMobile = !!ua.match(/AppleWebKit.*Mobile.*/);
  return {
    isiOS,
    isAndriod,
    isWeixin,
    isMobile
  };
})(window);

// 打开一个新的页面同时传参  post传参
// 通过虚拟表单的形式提交post请求，从而实现页面的跳转
// openPostWindow('https://www.baidu.com', params, '');
export function openPostWindow(url, data, name) {
  const tempForm = document.createElement('form');
  tempForm.id = 'tempForm1';
  tempForm.method = 'post';
  tempForm.action = url;
  tempForm.target = name || '_self';

  Object.keys(data).forEach(key => {
    const hideInput = document.createElement('input');
    hideInput.type = 'hidden';
    hideInput.name = key;
    hideInput.value = data[key];
    tempForm.appendChild(hideInput);
  });
  // 注册事件
  if (document.all) {
    // document.all可以判断浏览器是否是IE
    tempForm.attachEvent('onsubmit', function() {}); // IE
  } else {
    tempForm.addEventListener('submit', function() {}, false); // firefox
  }
  document.body.appendChild(tempForm);
  // 触发事件
  if (document.all) {
    // document.all可以判断浏览器是否是IE
    tempForm.fireEvent('onsubmit');
  } else {
    tempForm.dispatchEvent(new Event('submit'));
  }
  tempForm.submit();
  document.body.removeChild(tempForm);
}

export const formatZero = val => (val < 10 ? `0${val}` : `${val}`);

export const getYMD = () => {
  // 获取当前年月日
  const curDate = new Date();
  const year = curDate.getFullYear();
  let month = curDate.getMonth() + 1;
  month = formatZero(month);
  let day = curDate.getDate();
  day = formatZero(day);
  const date = year + month + day;
  return date;
};

export const pages = (list, pageNum = 8) => {
  /*const arr = [];
  let minArr = [];
  list.forEach(item => {
    if (minArr.length === pageNum) {
      minArr = [];
    }
    if (minArr.length === 0) {
      arr.push(minArr);
    }
    minArr.push(item);
  });
  return arr;*/

  const pages = [];
  list.forEach((item, index) => {
    const page = Math.floor(index / pageNum);
    if (!pages[page]) {
      pages[page] = [];
    }
    pages[page].push(item);
  });
  return pages;
};

export {
  getNewQrImg,
  formatImgUrl,
  formatDuring,
  elementIsInFocus,
  isAppleDevice
};
